<template>
  <div class="container">
    <el-table :data="tableData" border class="table" row-key="id">
      <el-table-column prop="deptName" label="部门名称"></el-table-column>
      <el-table-column prop="orderNum" label="排序"></el-table-column>
      <el-table-column prop="createTime" label="创建时间"></el-table-column>
      <el-table-column label="操作" width="180">
        <template #default="scope">
          <el-button
            @click="handleAdd(scope.$index, scope.row)"
            icon="Plus"
            circle
          />
          <el-button
            @click="handleEdit(scope.$index, scope.row)"
            icon="Edit"
            circle
          />
          <el-button
            @click="handleDelete(scope.$index, scope.row)"
            icon="Delete"
            circle
          />
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination">
      <el-pagination
        background
        layout="total, prev, pager, next"
        :current-page="query.pageIndex"
        :page-size="query.pageSize"
        :total="pageTotal"
        @current-change="handlePageChange"
      ></el-pagination>
    </div>

    <!-- 编辑弹出框 -->
    <el-dialog :title="title" v-model="editVisible" center @close="cancelEdit">
      <el-form
        :model="row"
        :rules="rules"
        ref="form"
        label-width="100px"
        size="small"
      >
        <el-form-item prop="deptName" label="部门名称">
          <el-input v-model="row.deptName" placeholder="用户名"></el-input>
        </el-form-item>
        <el-form-item prop="parentId" label="上级部门">
          <el-select v-model="row.parentId" placeholder="上级部门">
            <el-option
              v-for="item in deptOptions"
              :key="item.id"
              :label="item.deptName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="orderNum" label="排序">
          <el-input v-model="row.orderNum" placeholder="排序"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span>
          <el-button @click="cancelEdit">取 消</el-button>
          <el-button type="primary" @click="saveEdit">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { reactive, ref } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { addDept, deleteDept, listDept, updateDept } from "@/api/dept";

const rules = {
  deptName: [{ required: true, message: "请输入部门名称", trigger: "blur" }],
};
const query = reactive({
  pageNum: 1,
  pageSize: 10,
});
const tableData = ref([]);
const pageTotal = ref(0);
const title = ref("");
const editVisible = ref(false);
const row = reactive({});
const deptOptions = ref([]);
const form = ref(null);

// 获取部门列表
const queryDept = () => {
  listDept(query).then((res) => {
    tableData.value = res.data.rows;
    pageTotal.value = res.data.total;
  });
};

// 查询操作
const handleSearch = () => {
  query.pageNum = 1;
  queryDept();
};

// 分页导航
const handlePageChange = (val) => {
  query.pageNum = val;
  queryDept();
};

// 删除操作
const handleDelete = (index, row) => {
  // 二次确认删除
  ElMessageBox.confirm("确定要删除吗？", "提示", {
    type: "warning",
    confirmButtonText: "确定",
    cancelButtonText: "取消",
  }).then(() => {
    deleteDept(row.id).then(() => {
      ElMessage.success("删除成功");
      queryDept();
    });
  });
};

// 显示添加窗口
const handleAdd = (index, row) => {
  row = {};

  deptOptions.value = deptTreeDataToArr(tableData);
  deptOptions.value.push({ id: 0, deptName: "无" });

  row.parentId = row.id;
  title.value = "添加部门";
  editVisible.value = true;
};

// 显示修改窗口
const handleEdit = (index, row) => {
  deptOptions.value = deptTreeDataToArr(tableData, row.id);
  deptOptions.value.push({ id: 0, deptName: "无" });

  this.row = row;
  title.value = "编辑部门";
  editVisible.value = true;
};

// 取消修改
const cancelEdit = () => {
  editVisible.value = false;
  queryDept();
};

// 保存修改
const saveEdit = () => {
  form.value.validate((valid) => {
    if (valid) {
      if (title.value === "编辑部门") {
        updateDept(row).then(() => {
          ElMessage.success("更新成功");
          editVisible.value = false;
          queryDept();
        });
      } else {
        addDept(row).then(() => {
          ElMessage.success("添加成功");
          editVisible.value = false;
          queryDept();
        });
      }
    }
  });
};

// 部门树转数组
const deptTreeDataToArr = (data, id) => {
  const res = [];

  function dfs(tree) {
    const newTree = {
      id: tree.id,
      deptName: tree.deptName,
      parentId: tree.parentId,
    };
    res.push(newTree);
    if (tree.children) {
      for (const item of tree.children) {
        if (item.id === id) {
          break;
        }

        dfs(item);
      }
    }
  }

  for (const item of data) {
    if (item.id !== id) {
      dfs(item);
    }
  }
  return res;
};

queryDept();
</script>
